package com.itheima.web;

import com.itheima.pojo.User;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("consumer")
public class ConsumerController {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    DiscoveryClient discoveryClient;
    @GetMapping("{id}")
    @HystrixCommand(fallbackMethod = "queryByIdFullBack")
    public User queryById(@PathVariable("id") String username){

       // String url = "http://localhost:8081/user/"+username;
//        List<ServiceInstance> instances = discoveryClient.getInstances("USER-SERVICE");
//        ServiceInstance serviceInstance = instances.get(0);
//        String url = "http://" + serviceInstance.getHost() + ":" + serviceInstance.getPort() + "/user/" + username;
        String url = "http://user-service/user/" + username; // user-service 微服务名称
        if ("itheima".equals(username)) {
            throw new RuntimeException("太忙了哦");
        }
        User userMap = restTemplate.getForObject(url, User.class);
        System.out.println(userMap);
        return userMap;
    }

    public User queryByIdFullBack(String username) {
        User user = new User();
        user.setUsername(username);
        user.setName("暂停服务");
        return user;
    }
}